package com.cash.lemoloan.networklib.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import com.cash.lemoloan.networklib.Intetface.PhotoUploadCallBack;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PhotoUpload {
    private static final ExecutorService executorService = Executors.newCachedThreadPool();
    private final static String TAG = "PhotoUpload";
    private static final int MaxCount = 3;

    public static void upload(final Context context, final Bitmap bitmap, String url, PhotoUploadCallBack photoUploadCallBack) {
        executorService.execute(() -> {
            JSONObject data = new JSONObject();
            try {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                byteArrayOutputStream.flush();
                byte[] bitmapData = byteArrayOutputStream.toByteArray();
                String base64String = Base64.encodeToString(bitmapData, Base64.DEFAULT);
                data.put("userGid", "");
                data.put("appId", "Mopeso");
                data.put("channel", "MP");
                data.put("picture", base64String);
                byteArrayOutputStream.close();
            } catch (Exception e) {
            }

            bitmap.recycle();
            Counter counter = new Counter();
            while (counter.getCount() < MaxCount) {
                CountDownLatch countDownLatch = new CountDownLatch(1);
//                Log.d(TAG, "postPhotoMethod start " + counter.getCount());
                NetWorkUtils.postPhotoMethod(context, url, data.toString(), new StringCallback() {
                    public void onError(Call call, Exception e, int i) {
                        countDownLatch.countDown();
                        if (counter.getCount() == MaxCount - 1) {
                            photoUploadCallBack.onPhotoUploadFail();
                        }
//                        Log.d(TAG, "upload onError " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String s, int i) {
                        counter.setCount(MaxCount);
                        countDownLatch.countDown();
                        photoUploadCallBack.onPhotoUploadSuccess();
//                        Log.d(TAG, "upload success");
                    }
                });
                try {
                    countDownLatch.await();
                } catch (Exception e) {
                }
                counter.increment();
            }


        });

    }

    public static void saveBitmapToSDCard(final Bitmap bitmap) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                // 获取SD卡路径
                File sdCardDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                // 创建文件
                File imageFile = new File(sdCardDirectory.getAbsolutePath() + "/", System.currentTimeMillis() + ".jpg");
                FileOutputStream fileOutputStream = null;
                try {
                    imageFile.createNewFile();
                    // 创建文件输出流
                    fileOutputStream = new FileOutputStream(imageFile);
                    // 将Bitmap压缩为JPEG格式并写入文件
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    fileOutputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fileOutputStream != null) {
                            fileOutputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }


    static class Counter {
        private int count;

        public Counter() {
            this.count = 0;
        }

        public void increment() {
            count++;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

    }

}
